<?php

class M_gallery extends CI_Model {

	function __construct(){
		parent::__construct();
	}

	function gallery_get_count_rows($query){
		$sql="SELECT *
				FROM gallery
				WHERE publish='1'";
		$num_rows = $this->m_public_function->get_count_rows($sql);
		return $num_rows;
	}

	function gallery_listview($query, $start, $end){

		$sql="SELECT *
				FROM gallery

				WHERE publish='y'
				ORDER BY gallery_id DESC";

		$num_rows = $this->m_public_function->get_count_rows($sql);
		$sql.=" LIMIT $start, $end";
		//$this->firephp->log($sql);

		$query = $this->db->query($sql);
		if($query->num_rows()>0){
			return $query->result();
		}else{
			return null;
		}

	}

	function gallery_list($search_text, $start, $end){

		$sql="SELECT
				gallery_id,
				kat_id,
				thumb_image,
				gallery.desk,
				kategori,
				publish
			FROM
				gallery
			LEFT JOIN kategori ON (
				gallery.kat_id = kategori.id
			)
			WHERE gallery_id IS NOT NULL 
			";
		if($search_text != ''){
			$sql .= " AND ( lower(gallery.desk) LIKE '%".$search_text."%' 
			OR lower(kategori) LIKE '%".$search_text."%' 
			)";
		}
		$num_rows = $this->m_public_function->get_count_rows($sql);
		if($start != 0 && $end != 0){
			$sql.=" LIMIT $start, $end";
		}
		$query = $this->db->query($sql);

		if($num_rows > 0){
			$result = $query->result();
			$i = 0;
			foreach($result as $row){
				$data[$i] = $row;
				$i++;
			}
		}
		$final[] = array(
			"TotalRows"=>$num_rows,
			"results"=>$data
		);
		return json_encode($final);
	}

	function getDetail($id){
		$sql = "
			SELECT
				gallery_id,
				thumb_image,
				gallery.desk,
				publish,
				kat_id,
				kategori
			FROM gallery
			JOIN kategori ON gallery.kat_id = kategori.id
			WHERE gallery_id = ".$id."
		";
		$query = $this->db->query($sql);

		$num_rows = $query->num_rows();
		if($num_rows > 0){
			return $query->row();
		}
	}

	function gallery_save($params){
		extract($params);
		if($task == 'create'){
			$this->db->insert('gallery',$data);
		}else{
			$this->db->where('gallery_id', $id);
			$this->db->update('gallery',$data);
		}
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}

	function gallery_delete($id){
		$this->db->where('gallery_id',$id);
		$this->db->delete('gallery');
		if($this->db->affected_rows()){
			return 1;
		}else{
			return 0;
		}
	}

}